﻿
using Business.Base.DB.Query;
using Business.Base.Enums;
using Business.Base.Model;
using Business.Base.Service.impl;
using Configuration;
using PLC.Base;
using PLC.Manager;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Business.Base.Service
{

    /// <summary>
    /// ExperimentService提供接口，实现了一个试验从创建，到试验数据读取，数据计算，存储以及加载展示的闭环。
    /// 它依赖了硬件数据读取服务IEnvDataManager，数据库服务IExperimentDBService，数据计算服务ICaculateService
    /// 并且组织这三个服务完成试验流程的所有闭环。
    /// </summary>
    public class ExperimentService
    {

        IEnvDataManager        envDataManager;
        IExperimentDBService   experimentDBService;
        ExperimentExcelService experimentExcelService;
        ICaculateService       caculateService;

        /// <summary>
        /// 生成试验编号
        /// </summary>
        /// <returns></returns>
        public static string GenerateExperimentCode(ExperimentType experimentType)
        {
            //String code = experimentType.ToString() + "-" + string.Format("{0:yyyyMMddHHmmssffff}", DateTime.Now);
            String filePath = Config.GeneratorConfigPath;
            string currentDate = DateTime.Now.ToString("yyyy-MM-dd"); // 获取当前日期  
            
            try
            {
                // 读取文件内容  
                string content = File.ReadAllText(filePath);
                String generateCode = "";
                // 检查配置项是否已经存在  
                if (content.Contains("date=") && content.Contains("id="))
                {
                    // 从文件中获取配置项的值  
                    string[] lines = content.Split(new[] { Environment.NewLine, "\r\n", "\n\r", "\t","\n" }, StringSplitOptions.None);
                    var dateLine = lines.FirstOrDefault(line => line.Contains("date="));
                    var idLine = lines.FirstOrDefault(line => line.Contains("id="));

                    if (dateLine != null && idLine != null)
                    {
                        // 从配置项中获取日期和编号  
                        string date = dateLine.Substring(5); // 去掉前缀"date="  
                        string id = idLine.Substring(3); // 去掉前缀"id="  

                        // 检查当前日期是否等于配置日期  
                        if (date == currentDate)
                        {
                            int code = int.Parse(id);
                            generateCode = DateTime.Now.ToString("yyyyMMdd") + "-"+(10000+code).ToString().Substring(1,4);
                            content = $"date={currentDate}\nid=" + (code+1);
                            File.WriteAllText(filePath, content); // 将更新后的内容写回文件
                            return generateCode;
                        }
                        else
                        {
                            // 如果当前日期不等于配置日期，更新配置项为当前日期和编号1  
                            content = $"date={currentDate}" + "\n" + $"id=2";
                            File.WriteAllText(filePath, content); // 将更新后的内容写回文件  
                            generateCode = DateTime.Now.ToString("yyyyMMdd") + "-" + (10000 +  1).ToString().Substring(1, 4);
                            return generateCode;

                        }
                    }            
                      
                  
                }
                // 如果当前日期不等于配置日期，更新配置项为当前日期和编号1  
                content = $"date={currentDate}" + "\n" + $"id=1";
                File.WriteAllText(filePath, content); // 将更新后的内容写回文件  
                generateCode = DateTime.Now.ToString("yyyyMMdd") + 1;
                return generateCode;

            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
                throw ex;
            }
        }  
           




        public ExperimentService(IExperimentDBService experimentDBService, ICaculateService caculateService, ExperimentExcelService experimentExcelService)
        {
            envDataManager = EnvDataManagerSimpleFactory.createEnvDataManager(EnvDataConfig.EnvDataType);
            this.experimentDBService = experimentDBService;
            this.caculateService = caculateService;
            this.experimentExcelService = experimentExcelService;
            //this.experiment = exp;
        }
        

        /// <summary>
        /// 打开连接，开始读取数据
        /// </summary>
        public virtual void StartRead()
        {
            envDataManager.Open();
            //envDataManager.Connect();
        }

        /// <summary>
        /// 从硬件读取数据
        /// </summary>
        /// <param name="transformationRatio"></param>
        /// <returns></returns>
        public virtual EnvData FetchDataFromEnv(DynamicParams dynamicParams)
        {            
            return envDataManager.ReadData(dynamicParams);
            //return envDataManager.ReadData(dn,transformationRatio);
        }

        public virtual void FetchData()
        {
            this.envDataManager.FetchData();
        }


        /// <summary>
        /// 关闭连接，结束数据读取
        /// </summary>
        public virtual void EndRead()
        {
            envDataManager.Close();
        }

        /// <summary>
        /// 实验基础数据更新后，重新计算试验记录数据
        /// </summary>
        public virtual void ReCaculateRecord(Experiment experiment)
        {
            this.caculateService.ReCaculateRecord(experiment);
        }


        public virtual ExperimentRecord CaculateDataFromRecord(Experiment experiment,EnvData data)
        {
           return this.caculateService.CaculateDataFromRecord(experiment,data);
        }

        public virtual BaseChartData CaculateChartData(Experiment experiment)
        {
            return this.caculateService.CaculateChartData(experiment);
        }

        public virtual void CaculateExperimentResult(ref Experiment experiment )
        {
            this.caculateService.CaculateExperimentResult(ref experiment); 
        }

        public virtual List<Object> QueryExperiment(BaseQuery query)
        {
            return this.experimentDBService.QueryExperiment(query);
        }

        public virtual List<Object> QueryExperimentRecord(BaseQuery query)
        {
            return this.experimentDBService.QueryExperimentReocrd(query);
        }

        public virtual int GetExperimentCount(BaseQuery query)
        {
            return this.experimentDBService.GetExperimentCount(query);
        }

        public virtual int GetExperimentRecordCount(BaseQuery query)
        {
            return this.experimentDBService.GetExperimentRecordCount(query);
        }

        public virtual void DeleteExperiment(Experiment experiment)
        {
            this.experimentDBService.DeleteExperiment(experiment);
        }

        public virtual void SaveExperiment(Experiment experiment)
        {
            this.experimentDBService.SaveExperiment(experiment);
        }

        public virtual void UpdateExperiment(Experiment experiment)
        {
            this.experimentDBService.UpdateExperiment(experiment);
        }

        public virtual void SaveExperimentReport(Experiment experiment,String saveFile=null)
        {
             experimentExcelService.SaveExperiment(experiment,saveFile); 
        }

        public virtual void FinishExperiment(Experiment experiment)
        {

            this.SaveExperimentReport(experiment);
            this.SaveExperiment(experiment);
        }

        public virtual void RemoveExperimentRecordByIds(int[] id)
        {
            this.experimentDBService.RemoveExperimentRecordByIds(id);
        }

        public virtual int SaveExperimentRecord(ExperimentRecord record)
        {
            return this.experimentDBService.SaveExperimentRecord(record);
        }

        public void UpdateExperimentRecord(ExperimentRecord record)
        {
            this.experimentDBService.UpdateExperimentRecord(record);
        }
    }
}
